const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../config/config');
const { sendError } = require('../utils/response');

module.exports = {
  // 用户注册
  async register(username, email, password, phone, role = 'customer') {
    const hashedPassword = await bcrypt.hash(password, 10);
    const [result] = await db.execute(
      'INSERT INTO users (username, email, password, phone, role) VALUES (?, ?, ?, ?, ?)',
      [username, email, hashedPassword, phone, role]
    );
    return result.insertId;
  },

  // 用户登录
  async login(email, password) {
    const [users] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
    
    if (users.length === 0) {
      throw new Error('用户不存在');
    }

    const user = users[0];
    const isMatch = await bcrypt.compare(password, user.password);
    
    if (!isMatch) {
      throw new Error('密码错误');
    }

    const token = jwt.sign(
      { id: user.id, username: user.username, role: user.role },
      config.jwtSecret,
      { expiresIn: config.jwtExpiresIn }
    );

    return {
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        avatar: user.avatar,
        role: user.role
      },
      token
    };
  },

  // 获取用户信息
  async getUserById(id) {
    const [users] = await db.execute('SELECT id, username, email, phone, avatar, role FROM users WHERE id = ?', [id]);
    return users[0];
  },

  // 更新用户信息
  async updateUser(id, data) {
    const fields = [];
    const values = [];
    
    for (const [key, value] of Object.entries(data)) {
      if (value !== undefined) {
        fields.push(`${key} = ?`);
        values.push(value);
      }
    }
    
    if (fields.length === 0) {
      throw new Error('没有可更新的字段');
    }
    
    values.push(id);
    const query = `UPDATE users SET ${fields.join(', ')} WHERE id = ?`;
    const [result] = await db.execute(query, values);
    return result.affectedRows > 0;
  },

  // 更新用户头像
  async updateAvatar(id, avatarPath) {
    const [result] = await db.execute('UPDATE users SET avatar = ? WHERE id = ?', [avatarPath, id]);
    return result.affectedRows > 0;
  },

  // 获取所有用户(带分页和搜索)
  async getAllUsers({ page = 1, limit = 10, keyword }) {
    const offset = (page - 1) * limit;
    let query = 'SELECT id, username, email, phone, avatar, role, created_at FROM users WHERE 1=1';
    const params = [];

    if (keyword) {
      query += ' AND (username LIKE ? OR email LIKE ? OR phone LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`);
    }

    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(parseInt(limit), parseInt(offset));

    const [users] = await db.execute(query, params);

  
    
    // 获取总数用于分页
    let countQuery = 'SELECT COUNT(*) as total FROM users WHERE 1=1';
    const countParams = params.slice(0, -2); // 移除LIMIT和OFFSET参数

    if (keyword) {
      countQuery += ' AND (username LIKE ? OR email LIKE ? OR phone LIKE ?)';
    }

    const [total] = await db.execute(countQuery, countParams);

    return {
      users,
      pagination: {
        total: total[0].total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total[0].total / limit)
      }
    };
  },
};